<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\admin\model;

use api\admin\model\BandToiletModel;
use api\admin\model\ToiletFlowModel;
use api\common\model\CommonModel;

class ToiletDeviceModel extends CommonModel
{
    // 可查询字段
    // protected $visible = [
    //     'id', 'start_time', 'end_time', 'man_num', 'woman_num','flow_num','titile','position','create_time',
    // ];
    //模型关联方法
    // protected $relationFilter = ['articles'];

    /**
     * 基础查询
     */
    // protected function base($query)
    // {
    //     $query->alias('toilet')->where('toilet.status', 1);
    // }
    /**
     * 关联
     * @return $this
     */
    // public function articles()
    // {
    //     return $this->belongsToMany('PortalPostModel','portal_tag_post','post_id','tag_id');
    // }

    /**
     * [DetailsProportion 获取公厕使用比例]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $mac      [description]
     * @param    [type]     $type     [description]
     * @param    [type]     $userTime [description]
     * @param    [type]     $dateTime [description]
     */
    public function DetailsProportion($mac, $type, $userTime, $dateTime)
    {

        $ToiletFlow = new ToiletFlowModel();
        // print_r($userTime);
        // echo "\n";
        // print_r($dateTime);
        // exit();
        //判断当前是否总流量设备
        if ($this->getFlowStatus($mac))
        {
            //
            $result['label'] = ['总流量'];
            //获取总流量
            $Details       = $ToiletFlow->getDetailsNumber($mac, $type, $userTime, $dateTime);
            $result['num'] = [array_sum($Details)];
        }
        else
        {
            $label           = $this->getDetailsProportionLabel($mac);
            $result['label'] = $this->labelToStr($label)['label'];

            //查询流量设备中的数据

            $Details = $this->getDetailsProportionNum($mac, $this->labelToStr($label)['ids'], $type, $userTime, $dateTime);
            $result['num'] = $Details;

            //查询坑位设备中的数据 
            // $Details       = $this->getDetailsProportionNum($mac, $this->labelToStr($label)['ids'], $type, $userTime, $dateTime);
        }
        return $result;

    }

    
    /**
     * [getFlowStatus 获取当前流量设备状态]
     * @return [type] [description]
     */
    public function getFlowStatus($mac)
    {
        $BandToilet = new BandToiletModel();
        return $BandToilet->where([
            'master_mac' => $mac,
            'tag_id' => 9,
            'mac_device_type' => 1,
        ])->count();

    }

    /**
     * [getDetailsProportionNum 动态生成数量]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $mac      [description]
     * @param    [type]     $ids      [description]
     * @param    [type]     $type     [description]
     * @param    [type]     $userTime [description]
     * @param    [type]     $dateTime [description]
     * @return   [type]               [description]
     */
    public function getDetailsProportionNum($mac, $ids, $type, $userTime, $dateTime)
    {
        // $BandToilet = new BandToiletModel();

        switch ($type)
        {
            case '3':
                return $this->getYearDetails($mac, $ids, $userTime, $dateTime);
                break;
            case '2':
                return $this->getMonthDetails($mac, $ids, $userTime, $dateTime);
                break;
            default:
                return $this->getDefaultDetails($mac, $ids, $userTime, $dateTime);
                break;
        }

    }

    /**
     * [getDefaultDetails 7/30数据查询]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @return   [type]     [description]
     */
    public function getDefaultDetails($mac, $ids, $userTime, $dateTime)
    {

        $ToiletFlow = new ToiletFlowModel();
        foreach ($ids as $key => $value)
        {
            $result = $ToiletFlow->alias("a")->field('FROM_UNIXTIME(a.create_time, "%m-%d") as times,sum(device_status) as in_num')
                ->join('band_toilet t', 't.mac = a.mac', 'LEFT')
                ->where(['t.tag_id' => $value, 'a.master_mac' => $mac])
                ->whereTime('a.create_time', -count($dateTime) . ' days')
                ->group('times')
                ->select()->toArray();
            $num[] = isset($result[0]['in_num']) ? $result[0]['in_num'] : 0;
        }

        return $num;
    }

    /**
     * [getgetMonthDetails 获取月份数据]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getMonthDetails($mac, $ids, $userTime, $dateTime)
    {

        $ToiletFlow = new ToiletFlowModel();
        $tmp        = $ToiletFlow->getMonth($userTime);

        foreach ($ids as $key => $value)
        {
            $result = $$ToiletFlow->alias("a")->field('FROM_UNIXTIME(a.create_time, "%Y-%m") as times,sum(device_status) as in_num')
                ->join('band_toilet t', 't.mac = a.mac', 'LEFT')
                ->where(['t.tag_id' => $value, 'a.master_mac' => $mac])
                ->whereTime('a.create_time', 'between', [strtotime($tmp['start_time']), strtotime($tmp['end_time'])])
                ->group('times')
                ->select()->toArray();
            $num[] = isset($result[0]['in_num']) ? $result[0]['in_num'] : 0;

        }
        return $num;
    }

    /**
     * [getgetYearDetails 获取年度数据]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]      $mac      [description]
     * @param    [type]     $ids      [description]
     * @param    [type]     $userTime [description]
     * @param    [type]     $dateTime [description]
     * @return   [type]               [description]
     */
    public function getYearDetails($mac, $ids, $userTime, $dateTime)
    {

        $ToiletFlow = new ToiletFlowModel();

        $num = [];
        if (strlen($userTime) == 4)
        {

            foreach ($ids as $key => $value)
            {

                // $result = $this->alias("a")->field('FROM_UNIXTIME(a.create_time, "%Y-%m") as times,sum(device_status) as in_num')
                $result = $$ToiletFlow->alias("a")->field('FROM_UNIXTIME(a.create_time, "%Y-%m") as times,sum(device_status) as in_num')
                    ->join('band_toilet t', 't.mac = a.mac', 'LEFT')
                    ->where(['t.tag_id' => $value, 'a.master_mac' => $mac])
                    ->whereTime('a.create_time', 'between', [$userTime . '-1-1', $userTime . '-12-31'])
                    ->group('times')
                    ->select()->toArray();
                $num[] = isset($result[0]['in_num']) ? $result[0]['in_num'] : 0;

            }

            return $num;
        }
    }

    /**
     * [getDetailsProportionLabel 获取公厕类型]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $mac [description]
     * @return   [type]          [description]
     */
    public function getDetailsProportionLabel($mac)
    {
        $BandToilet = new BandToiletModel();
        return $BandToilet->alias("a")
            ->field('t.id,t.tag_name')
            ->join('band_toilet_tag t', 't.id = a.tag_id', 'LEFT')
            ->where(['master_mac' => $mac, 'mac_device_type' => 2])
            ->group('t.id')
            ->select();
    }

    /**
     * [labelToStr 转为字符串数组]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $obj [description]
     * @return   [type]          [description]
     */
    public function labelToStr($obj)
    {
        foreach ($obj as $key => $value)
        {
            $tmpValue[] = $value['tag_name'];
            $tmpId[]    = $value['id'];
        }

        return ['ids' => $tmpId, 'label' => $tmpValue];
    }

    /**
     * [getToiletFields 获取单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function getToiletDeviceFields($id, $fields = '*')
    {
        if (is_array($id))
        {
            return $this->field($fields)->where($id)->find();

        }
        else
        {
            return $this->field($fields)->where('id', $id)->find();
        }

    }

    /**
     * [getToiletFields 更新单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function updateToiletDeviceFields($id, $update = [])
    {

        if (is_array($id))
        {
            return $this->where($id)->update($update);
        }
        else
        {
            return $this->where('id', $id)->update($update);
        }
    }

}
